package cur.nature.log.service;

import cur.nature.framework.core.util.FileUtil;
import cur.nature.log.model.Log_CommonVO;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 日志数据 Service
 * 作者：Auto Generator By wujian
 * 生成日期：2023-07-09 16:05:31
 */
@Slf4j
@Service
@ConditionalOnProperty( value = {"cur.component.log.enable"})
public class Log_CommonService  {

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${server.port}")
    private Integer port;

    @Value("${logging.file.path}")
    private String filePath;

    public List<Log_CommonVO.list_Res> queryByTraceId(Log_CommonVO.list_Param param) {

        final List<Log_CommonVO.list_Res> list = new ArrayList<>();
        final String logFileName = applicationName +"_"+port+ ".log";
        final String filePathStr = filePath+ File.separator+logFileName;
        // 校验日志文件
        if (!FileUtil.isFileExists(filePathStr)) {
            final Log_CommonVO.list_Res tmp = new Log_CommonVO.list_Res();
            tmp.setFilePath(filePathStr);
            tmp.setLog(Arrays.asList("无法定位日志文件: " + filePathStr));
            list.add(tmp);
            return list;
        }
        // 读取本地日志
        final List<String> result = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePathStr))) {
            final Log_CommonVO.list_Res tmp = new Log_CommonVO.list_Res();
            tmp.setFilePath(filePathStr);
            tmp.setFileUrl("/component/log/v1/api/download");
            tmp.setLog(result);
            list.add(tmp);
            // 读取
            String line;
            int lineNum = 0;
            boolean startFlag = false;
            while ((line = reader.readLine()) != null) {
                if (line.contains(param.getTraceId()) || startFlag) {
                    startFlag = true;
                    if (line.indexOf(param.getTraceId()) != -1) {
                        line = line.replace(param.getTraceId(), "<span style='color:red;'>" + param.getTraceId() + "</span>");
                    }
                    if (line.startsWith("\tat")) {
                        line = ("<span style='color:red;'>" + line + "</span>");
                    }
                    result.add(line+"<br />");
                    if (line.contains("请求结束:")) {break;}
                }
                if (startFlag) {lineNum++;}
                if (lineNum > 500) {break;}
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        if (result.isEmpty()) {
            result.add("查询结果为空: " + param.getTraceId());
        }

        return list;
    }

    public String download(HttpServletResponse response) {
        final String fileName = applicationName + "_" + port + ".log";
        final String filePathStr = filePath + File.separator + fileName;
        // 指定要下载的文件
        File file = new File(filePathStr);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) {
                final OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "下载失败";
    }
}

